<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/14 0014
 * Time: 下午 3:41
 */
namespace app\admin\controller;

use app\admin\model\OrderAfterSale;
use app\admin\model\OrderDistribution;
use app\admin\model\Orderitem;
use app\admin\model\ProductBatchStock;
use app\common\DictConstant;
use app\common\model\ExpressTrace;
use app\lib\redis\Redis;
use think\Db;
use think\Exception;
use think\Request;

class Aftersale extends Base{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = 'order_after_sale';
        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['o.old_status'] = ['neq',7];
        $this->defaultWhere = $defaultWhere;
        $status = get_order_status();
        $method = get_deliver_method();
        $this->assign('status',$status);
        $this->assign('method',$method);
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        $model = model($this->model);
        if ($request->isAjax()){
            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            // 排序条件
            $order = 'a.create_date DESC';
            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }
            $join = [
                ['__MEMBER__ m','m.account_number=a.member_phone'],
                ['__ORDER_ITEM__ o','o.id=a.order_item_id']
            ];
            $fields = 'a.id,a.member_phone,a.order_id,a.order_item_id,a.out_refund_no,a.refund_fee,a.old_total,a.create_date,a.damage_type,a.status,m.account_number,m.name,o.product_name,o.old_status';
            $data = $model->alias('a')
                ->join($join)
                ->where($where)
                ->field($fields)
                ->limit($start,$length)
                ->order($order)
                ->select();

            if (!$data){
                return $this->error('未查询到数据');
            }
            $count = $model->alias('a')
                ->join($join)
                ->where($where)
                ->field($fields)
                ->count();

            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }
        return $this->view->fetch($this->indexView,[
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    public function detail(){
        $param = $this->request->param();
        $model = model($this->model);
        $id = $param['id'];
        $info = $model->alias('a')
            ->join('order o','o.id=a.order_id')
            ->where('a.id',$id)
            ->field('a.id,a.order_id,a.refund_fee,a.status,a.old_total,a.out_refund_no,a.create_date,a.member_phone,a.end_date,a.content,o.pay_method,o.status as ostatus')
            ->find();
        $info['refund_fee'] = sprintf("%.2f",$info['refund_fee']/100);
        $info['old_total'] = sprintf("%.2f",$info['old_total']/100);
        $this->assign('info',$info);
        if($this->request->isAjax()){
            $join = [
                ['__PRODUCT__ p','p.id=a.product_id'],
                ['__ORDER__ o','o.id=a.order_id']
            ];
            $fields = 'a.id,a.damage_type,a.reason,a.reason_des,a.count,a.imgs,p.name,o.pay_method';
            $order = db('order_after_sale')->alias('a')
                ->where('a.id',$id)
                ->join($join)
                ->field($fields)
                ->select();
            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $order
            ];

            return json($result);
        }


        return $this->view->fetch('detail',[
            'pageSize' => ['url' => fullUrl($this->request->path())],
            'searchFields' => $this->searchFields,
            'param' => $this->request->param()
        ]);
    }

    /**
     * 拒绝售后
     * @param Request $request
     */
    public function refuse_aftersale(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id']) || empty($param['content'])){
                return $this->error('参数异常');
            }
            if(mb_strlen($param['content'],'utf-8') > 50){
                return $this->error('最大只能输入50个字');
            }
            Db::startTrans();
            try{
                $after_sale = OrderAfterSale::where('id',$param['id'])->find();
                if($after_sale){
                    if($after_sale['status'] == 1){
                        $after_sale->status = DictConstant::AfterSale_Refuse;
                        $after_sale->content = $param['content'];
                        $after_sale->save();
                        Orderitem::where('id',$after_sale['order_item_id'])->update(['after_sale_status'=>DictConstant::AfterSale_Refuse]);
                        Db::commit();
                        return $this->success('操作成功');
                    }else{
                        return $this->error('售后订单状态异常');
                    }
                }else{
                    return $this->error('售后订单不存在');
                }
            }catch (Exception $ex){
                Db::rollback();
                return $this->error($ex->getMessage());
            }
        }else{
            return $this->error('非法请求');
        }


    }

    /**
     * 同意售后
     * @param Request $request
     */
    public function agree_aftersale(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id'])){
                return $this->error('参数异常');
            }
            Db::startTrans();
            try{
                $after_sale = OrderAfterSale::where('id',$param['id'])->find();
                if($after_sale){
                    if($after_sale['status'] == 1){
                        $Orderitem = Orderitem::where('id',$after_sale['order_item_id'])->find();
                        $Orderitem->after_sale_status = 2;
                        if(in_array($Orderitem['old_status'],[2,6])){
                            //没发发货，没有提货
                            $after_sale->status = DictConstant::AfterSale_Pendingrefund;
                            //还原库存sock表
                            $this->updatesock($Orderitem['product_id'],$Orderitem['count']);
                        }elseif (in_array($Orderitem['old_status'],[3,4,11])){
                            //已经发货了
                            $after_sale->status = DictConstant::AfterSale_Tobereturned;
                        }elseif ($Orderitem['old_status'] == 7){
                            //已经提货
                            $after_sale = DictConstant::AfterSale_Store;
                        }
                        $after_sale->save();
                        $Orderitem->save();
                        Db::commit();
                        $count1 = Orderitem::where('order_id',$Orderitem['order_id'])->count();
                        $count2 = Orderitem::where('order_id',$Orderitem['order_id'])->where('after_sale_status','in',[2,4])->count();
                        if($count1 == $count2){
                            \app\admin\model\Order::where('id',$Orderitem['order_id'])->update(['status'=>DictConstant::Order_AllAfter]);
                        }
                        return $this->success('操作成功');
                    }else{
                        return $this->error('售后订单状态异常');
                    }
                }else{
                    return $this->error('售后订单不存在');
                }

            }catch (Exception $ex){
                Db::rollback();
                return $this->error($ex->getMessage());
            }

        }else{
            return $this->error('非法请求');
        }
    }

    private function updatesock($product_id,$count){
        \app\admin\model\Stock::where('product_id',$product_id)->setInc('marketable',$count);
    }

    /**
     * 确认退款
     * @param Request $request
     */
    public function confirm_refund(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(!empty($param['id'])){
                $Aftersale = new \app\admin\service\Aftersale($param);
                $info = $Aftersale->actionrefund();
                if($info['pass']){
                    return $this->success('退款成功');
                }else{
                    return $this->error($info['msg']);
                }
            }else{
                return $this->error('参数异常');
            }
        }else{
            return $this->error('非法请求');
        }

    }

    /**
     * 用户售后寄回商品物流
     * @param Request $request
     */
    public function show_wuliu(Request $request){
        $param = $request->param();
        if(!empty($param['aftersale_id'])){
            $order_after_sale = db('order_after_sale')->where('id',$param['aftersale_id'])->find();
            if($order_after_sale){
                if($order_after_sale['status'] == 5){
                    if($order_after_sale['express_name'] && $order_after_sale['express_no']){
                        $data['ShipperCode'] = $order_after_sale['express_name'];
                        $data['LogisticCode'] = $order_after_sale['express_no'];
                        $redis = Redis::getRedisConn();
                        $result = $redis->get('wuliu' . $order_after_sale['express_no']);
                        if(!$result){
                            $Express = new \app\lib\express\Express();
                            $res = $Express->getOrderTracesByJson($data);
                            if($res['Success']){
                                if(is_array($res['Traces'])){
                                    $wuliuinfo = array_reverse($res['Traces']);
                                    $wuliujson = json_encode($wuliuinfo);
                                    $redis->set('wuliu' . $order_after_sale['express_no'],$wuliujson,600); //查询缓存10分钟
                                }else{
                                    return $this->error('物流信息异常');
                                }
                            }else{
                                return $this->error('暂无物流信息');
                            }
                        }else{
                            $wuliuinfo = json_decode($result,true);
                        }
                        $Express = \app\admin\model\Express::where('code',$order_after_sale['express_name'])->find();
                        $expressinfo['name'] = $Express->name;
                        $expressinfo['express_no'] = $order_after_sale['express_no'];
                        return $this->fetch('',[
                            'wuliuinfo' => $wuliuinfo,
                            'expressinfo' => $expressinfo
                        ]);
                    }else{
                        return $this->error('快递信息异常');
                    }
                }else{
                    return $this->error('售后订单状态异常');
                }
            }else{
                return $this->error('该售后订单不存在');
            }
        }else{
            return $this->error('参数异常');
        }
    }

    /**
     * 后台确认收到用户寄回来的货品
     * @param Request $request
     */
    public function confirm_receipt(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(!empty($param['id'])){
                Db::startTrans();
                try{
                    $OrderAfterSale = OrderAfterSale::where('id',$param['id'])->find();
                    if($OrderAfterSale){
                        if($OrderAfterSale->status == 5){
                            $OrderAfterSale->status = 6;
                            $OrderAfterSale->save();
                            //货品入库
                            $info = $this->warehousing($OrderAfterSale->order_id,$OrderAfterSale->product_id,$OrderAfterSale->count);
                            Db::commit();
                            if($info){
                                return $this->success('入库成功');
                            }else{
                                return $this->error('入库失败');
                                Db::rollback();
                            }
                        }
                    }else{
                        return $this->error('售后订单不存在');
                    }
                }catch (Exception $ex){
                    Db::rollback();
                    return $this->error($ex->getMessage());
                }

            }else{
                return $this->error('参数异常');
            }
        }else{
            return $this->error('非法请求');
        }

    }


    private function warehousing($order_id,$product_id,$count){
        $OrderDistribution = OrderDistribution::where(['order_id'=>$order_id,'product_id'=>$product_id])->select();
        if($OrderDistribution){
           foreach ($OrderDistribution as $v){
               ProductBatchStock::where(['product_id'=>$product_id,'production_time'=>$v['production_time']])->setInc('num',$v['num']);
           }
           \app\admin\model\Stock::where('product_id',$product_id)->setInc('marketable',$count);

            return true;

        }else{
            return false;
        }
    }


    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['order_no']) && $param['order_no']){
            $where['order_no'] = ['like', '%'.$param['order_no'].'%'];
        }
        if(isset($param['user_id']) && $param['user_id']){
            $where['member_id'] = $param['member_id'];
        }
        if(isset($param['deliver_method']) && $param['deliver_method']){
            $where['deliver_method'] = $param['deliver_method'];
        }
        if(isset($param['time']) && $param['time']){
            $where['time'] = str_replace('+','',$param['time']);
            $where['time'] = preg_replace('# #','',$where['time']);
            $where['time'] = explode ('到',$where['time']);
            $where['create_date'] = ['between',[$where['time'][0],$where['time'][1]]];
        }
        return $where;
    }

}